<style>
.tree {
  /*margin-top: 42px;*/
  /* border: 1px solid #d7dde4; */
  max-height: 600px;
  overflow-y: scroll;
}

.ztree li span {
  padding-bottom: 25px;
  /*margin-top: 20px;*/
  /*margin-bottom: 20px;*/
  /*border: 1px solid #ffffff;*/
  /*background: #f0f6e4;*/
  /*width:220px;height:360px;*/
  /*overflow-y:scroll;*/
  /*overflow-x:auto;*/
}
</style>

<template>
<Row class="layout-content-body">
  <!-- <Col span="4" class="tree">
    <div class="bg left tree">
        <ul id="treeD" class="ztree"></ul>
    </div>
    </Col> -->
  <Col span="24">
  <!-- <dtable :columns="columns" :dataAll="dataAll" :dataShow="dataShow" :loading="loading" director add delCheck assign check op @refresh="getall()" @add="add" @del="del" @edit="edit" @delCheck="delCheck" @assign="assign" @director="director"></dtable> -->
  <dtable :columns="columns" :data-all="dataAll" :data-show="dataShow" :loading="loading" add del-check check op @refresh="getall()" @add="add" @del="del" @edit="edit" @delCheck="delCheck" @assign="assign" />
  </Col>
  <Modal v-model="editData" title="学院信息" :mask-closable="false" class="editm" @on-ok="asyncOK" @on-cancel="asyncCancel">
    <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
      <Form-item label="名称" prop="Name">
        <Input
            v-model="formItem.Name"
            placeholder="请输入"
            @on-enter="asyncOK()"
          ></Input>
      </Form-item>
      <Form-item label="所属单位" prop="OrgId">
        <Select
            v-model="formItem.OrgId"
            disabled
            placeholder="请选择">
            <Option
              v-for="item in dataAll"
              :key="item.Id"
              :value="item.OrgId"
            >{{ item.OrgName }}</Option>
          </Select>
      </Form-item>
      <Form-item label="上级部门" prop="Pid">
        <Select
            v-model="formItem.Pid"
            placeholder="请选择"
          >
            <Option
              v-for="item in parentRes"
              :key="item.Id"
              :value="item.Id"
            >{{ item.Name }}</Option>
          </Select>
      </Form-item>
      <Form-item label="状态" prop="Status">
        <Radio-group v-model.number="formItem.Status" disabled>
          <Radio :label="1">启用</Radio>
          <Radio :label="0">停用</Radio>
        </Radio-group>
      </Form-item>
      <Form-item label="说明" prop="Remark">
        <Input
            v-model="formItem.Remark"
            type="textarea"
            :autosize="{minRows: 2,maxRows: 5}"
            placeholder="请输入..."
          >
                </Input>
      </Form-item>
    </Form>
  </Modal>
  <Modal v-model="directorFlag" :title="directorTitle" :mask-closable="false" class="editm">
    <Table stripe border highlight-row :columns="deptuserColumn" :data="directorData" />
  </Modal>
</Row>
</template>

<script>
// import '@s/plugins/zTree/js/jquery.ztree.core';
// import '@s/plugins/zTree/js/jquery.ztree.excheck';
// import '@s/plugins/zTree/js/jquery.ztree.exedit';
// import '@s/plugins/zTree/js/jquery.ztree.exhide';
// import 'font-awesome/css/font-awesome.css';
// import '@s/plugins/zTree/css/awesomeStyle/awesome.css';
// import { mapMutations, mapGetters, mapState } from 'vuex';
import dtable from '@/components/table/dtable.vue'; // 采用biztable
// import $ from 'jquery';
export default {
  components: {
    dtable
  },
  data () {
    return {
      loading: false, // 数据刷新遮罩层
      columns: [
        {
          title: '名称',
          key: 'Name',
          sortable: true
        },
        {
          title: '上级部门',
          key: 'Pname'
        },
        {
          title: '所属单位',
          key: 'OrgName',
          width: 280,
          sortable: true
        },
        {
          title: '状态',
          key: 'Sname',
          sortable: true
        }
      ], // 表格样式
      dataAll: [], // 表格数据来源
      dataShow: true, // 是否显示表格数据查看表单
      editData: false, // 显示编辑表单
      formItem: {
        Name: '',
        Pid: 0,
        Pname: '顶级部门',
        OrgId: '',
        OrgName: '',
        Status: 1,
        Remark: ''
      }, // 数据编辑表单
      ruleValidate: {
        Name: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'blur'
          }
        ],
        Pname: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          }
        ]
        //          Pid: [
        //            {required: true, message: '必须选择上级部门', trigger: 'change'},
        //          ],
      }, // 数据编辑表单验证规则
      addid: true, // true为修改模式，false为添加模式
      treeData: [],
      total: 0,
      setting: {
        view: {
          selectedMulti: false
        },
        check: {
          enable: false
        },
        data: {
          simpleData: {
            enable: true,
            rootPId: 0
          }
        },
        edit: {
          enable: true,
          showRemoveBtn: false,
          showRenameBtn: false
        },
        callback: {
          beforeDrag: this.beforeDrag,
          beforeDrop: this.beforeDrop
        }
      },
      zNodes: [],
      directorFlag: false,
      directorData: [],
      deptuserColumn: [
        {
          type: 'index',
          width: 60
        },
        {
          title: '名称',
          key: 'Name',
          sortable: true
        },
        // {
        //   title: "名称",
        //   key: "Remark",
        //   sortable: true
        // },
        {
          title: '姓名',
          key: 'Abbr',
          sortable: true
        },
        {
          title: '操作',
          render: (h, { row }) => {
            return h(
              'Button',
              {
                props: {
                  size: 'small',
                  type: 'primary'
                },
                on: {
                  click: () => {
                    // this.$Message.info(row.Id);
                    // console.log(row);
                    this.$api
                      .SetDeptDirector({
                        DeptId: this.deptTemp.Id,
                        UserId: row.Id
                      })
                      .then(res => {
                        if (res.code === 0) {
                          this.directorFlag = false;
                          this.$Message.success(
                            `已将${row.Abbr}设置为${this.deptTemp.Name}的主管！`
                          );
                        }
                      });
                  }
                }
              },
              '设置为主管'
            );
          }
        }
      ],
      deptName: '',
      deptTemp: {}
    };
  },
  computed: {
    // ...mapState(['isLogin', 'captchaUrl', 'cptId', 'msg', 'userInfo']),
    state () {
      return this.$store.state.app;
    },
    //      父部门
    parentRes () {
      let pr = [];
      // pr.push({
      //   Id:"0",
      //   Name: "顶级部门"
      // })
      for (let e in this.dataAll) {
        pr.push({
          Name: this.dataAll[e].Name,
          Id: this.dataAll[e].Id
        });
      }
      return pr;
    },

    directorTitle () {
      return `变更${this.deptName}主管`;
    }
  },
  watch: {},
  mounted () {
    this.getall();
  },
  methods: {
    director (rows) {
      // console.log(rows)
      if (rows.length && rows.length !== 1) {
        this.$Message.error('请选择一行！');
        return;
      }
      this.deptName = rows[0]['Name'];
      this.deptTemp = rows[0];
      this.$api
        .GetUserByDept({
          Id: rows[0].Id
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res.Data);
            this.directorData = res.Data;
            this.directorFlag = true;
          }
        });
    },
    beforeDrop (treeId, treeNodes, targetNode, moveType) {
      console.log(treeNodes);
      console.log(targetNode);
      // return targetNode ? targetNode.drop !== false : true;
      return !(
        targetNode == null ||
        (moveType !== 'inner' && !targetNode.parentTId)
      );
    },
    beforeDrag (treeId, treeNodes) {
      for (var i = 0, l = treeNodes.length; i < l; i++) {
        if (treeNodes[i].drag === false) {
          return false;
        }
      }
      return true;
    },
    //      改变页码
    getall () {
      this.loading = true;
      this.$api.GetDept().then(
        res => {
          if (!res.error) {
            this.dataAll = res.Data.tabledata;
            this.total = this.dataAll.length;
            // this.zNodes = res.Data.treedata;
            // $.fn.zTree.init($("#treeD"), this.setting, this.zNodes);
          } else {
            this.$Message.error(res.message);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    getOrganization () {
      this.spinShow = true;
      this.$api.getOrganizationList().then(
        res => {
          if (!res.error) {
            this.org = res.Data;
          } else {
            this.$Message.error(res.message);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    edit (index) {
      this.addid = true;
      this.formItem = index;
      this.editData = true;
    },
    add () {
      this.addid = false;
      this.$refs['editForm'].resetFields();
      this.formItem.OrgId = this.state.userInfo.Organization.Id;
      this.editData = true;
    },
    asyncOK () {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.addid) {
            this.$api.UpdateDept(this.formItem).then(
              res => {
                if (!res.error) {
                  this.getall();
                  this.$Message.success(res.message);
                } else {
                  this.$Message.error(res.message, 4);
                }
              },
              err => {
                if (err) {
                  this.$Message.error(err, 4);
                }
              }
            );
          } else if (!this.addid) {
            this.$api.AddDept(this.formItem).then(
              res => {
                if (!res.error) {
                  this.getall();
                  this.$Message.success(res.message);
                } else {
                  this.$Message.error(res.message, 4);
                }
              },
              err => {
                if (err) {
                  this.$Message.error(err, 4);
                }
              }
            );
          }
          setTimeout(() => {
            this.editData = false;
          }, 1000);
        } else {
          this.$Message.error('表单验证失败!');
        }
      });
      this.editData = false;
      this.$refs['editForm'].resetFields();
    },
    asyncCancel () {
      this.getall();
      this.$refs['editForm'].resetFields();
    },
    del (row) {
      this.$api.DeleteDept(row).then(
        res => {
          if (!res.error) {
            this.getall();
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    delCheck (row) {
      this.$api.DeleteDepts(row).then(
        res => {
          if (!res.error) {
            this.getall();
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    assign () {
      let treeObj = $.fn.zTree.getZTreeObj('treeD');
      let tee = treeObj.transformToArray(treeObj.getNodes());
      // console.log(tee);
      this.$api.AssignUserDept(tee).then(
        res => {
          if (!res.error) {
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    }
  }
};
</script>
